package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.admin.dao.SysMenuDao;
import com.shop.admin.dao.SysRoleMenuDao;
import com.shop.admin.entity.SysMenu;
import com.shop.admin.entity.SysRoleMenu;
import com.shop.admin.service.SysMenuService;

import com.shop.admin.service.SysRoleMenuService;
import com.shop.admin.utils.MenuHelper;
import com.shop.admin.vo.RoleMenuVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuDao, SysMenu> implements SysMenuService {

    @Resource
    private SysRoleMenuDao sysRoleMenuDao;

    @Resource
    private SysRoleMenuService sysRoleMenuService;

    @Override
    public List<SysMenu> findNodes() {
        List<SysMenu> sysMenuList = baseMapper.selectList(null);
        List<SysMenu> resultList = MenuHelper.bulidTree(sysMenuList);
        return resultList;
    }

    @Override
    public void doAssign(RoleMenuVo roleMenuVo) {
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        sysRoleMenu.setIsDeleted(1);
        sysRoleMenu.setUpdateTime(new Date());
        sysRoleMenuDao.update(sysRoleMenu,new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleMenuVo.getRoleId()));

        List<Integer> menuIdList = roleMenuVo.getMenuIdList();
        for (Integer menuId:menuIdList) {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(roleMenuVo.getRoleId());
            roleMenu.setCreateTime(new Date());
            roleMenu.setUpdateTime(new Date());
            roleMenu.setIsDeleted(0);
            sysRoleMenuService.save(roleMenu);
        }
    }

    @Override
    public List<SysMenu> findMenuByRoleId(String roleId) {
        List<SysMenu> menuList = baseMapper.selectList(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getStatus,1));

        List<SysRoleMenu> roleMenus = sysRoleMenuDao.selectList(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId,roleId));

        List<Integer> roleMenuIds = new ArrayList<>();
        for (SysRoleMenu sysRoleMenu:roleMenus) {
            Integer menuId = sysRoleMenu.getMenuId();
            roleMenuIds.add(menuId);
        }

        for (SysMenu sysMenu:menuList) {
            if(roleMenuIds.contains(sysMenu.getId())) {
                sysMenu.setSelect(true);
            } else {
                sysMenu.setSelect(false);
            }
        }

        List<SysMenu> sysMenus = MenuHelper.bulidTree(menuList);
        return sysMenus;
    }
}
